package com.zyx.enhancement.common;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.Map;

@Slf4j
public class HttpClientHelper {
    public static JSONObject getDataOnHttp(String url, Map<String, String> params) {
        return getDataOnHttp(url, params, new JSONObject());
    }

    public static JSONObject getDataOnHttp(String url, Map<String, String> params, JSONObject defaultResult) {
        JSONObject result = defaultResult;
        // 实例化http客户端
        OkHttpClient client = new OkHttpClient();
        // 创建URL对象
        HttpUrl.Builder queryUrlBuilder = HttpUrl.get(url).newBuilder();
        // 添加URL请求参数
        params.forEach(queryUrlBuilder::addQueryParameter);

        log.info("URL请求参数:{}", queryUrlBuilder.build().url());

        // 创建GET请求对象
        Request getRequest = new Request.Builder().url(queryUrlBuilder.build()).build();

        try {
            // 由客户端发起同步GET请求，并获得服务器回复(Response)对象
            Response response = client.newCall(getRequest).execute();
            // 判断请求是否成功
            if (response.isSuccessful()) {
                // 获取回应主体内容
                assert response.body() != null;
                String responseBody = response.body().string();
                // 处理响应数据
                log.info("[{}]---[{}]接口,返回-Raw-:{}", url, params, responseBody);
                result = JSON.parseObject(responseBody);
            } else {
                // 处理错误情况
                log.warn("获取[{}]---[{}]接口数据失败", url, params);
            }
        } catch (IOException e) {
            // 处理异常
            log.error(e.getMessage());
        }
        return result;
    }
}
